package com.pactera.miyuangroup.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 请求工具类
 *
 * @author Wangwu
 * @create 2018-04-23 下午5:07
 **/
@Slf4j
public class OkHttpUtils {

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String get(String url, Map<String, String> queries) {
        String responseBody = "";
        log.info("okhttp3 >> Get Url 提交的参数....");
        log.info("okhttp3 >> 请求类型 = GET");
        log.info("okhttp3 >> 请求地址URL = {}", url);
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = !url.contains("?");
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        log.info("okhttp3 >> 请求全路径 = {}", sb.toString());
        log.info("okhttp3 >> 开始请求......");
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            log.info("okhttp3 >> 请求响应码 = {}", status);
            if (response.isSuccessful()) {
                String str = response.body().string();
                log.info("okhttp3 >> 请求响应内容 = {}", str);
                return str;
            }
        } catch (Exception e) {
            log.error("okhttp3 >> 请求发送错误 = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
            log.info("okhttp3 >> 请求结束");
        }
        return responseBody;
    }


    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        String responseBody = "";
        log.info("okhttp3 >> Post Form 提交的参数....");
        log.info("okhttp3 >> 请求类型 = POST");
        log.info("okhttp3 >> 请求地址URL = {}", url);
        log.info("okhttp3 >> 请求数据类型 = {}", "MediaType >> application/x-www-form-urlencoded");
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                log.info("okhttp3 >> 请求参数 {} = {}", key, params.get(key));
                builder.add(key, params.get(key));
            }
        }
        log.info("okhttp3 >> 开始请求......");
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            log.info("okhttp3 >> 请求响应码 = {}", status);
            if (response.isSuccessful()) {
                String str = response.body().string();
                log.info("okhttp3 >> 请求响应内容 = {}", str);
                return str;
            }
        } catch (Exception e) {
            log.error("okhttp3 >> 请求发送错误 = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
            log.info("okhttp3 >> 请求结束");
        }
        return responseBody;
    }


    /**
     * post
     *
     * @param url     请求的url
     * @param params  post form 提交的参数
     * @param charset 编码，默认utf-8
     * @return
     */
    public static String post(String url, Map<String, String> params, String charset) {
        String responseBody = "";
        if (StringUtils.isBlank(charset)) {
            charset = "utf-8";
        }
        log.info("okhttp3 >> Post Form 提交的参数....");
        log.info("okhttp3 >> 请求类型 = POST");
        log.info("okhttp3 >> 请求地址URL = {}", url);
        log.info("okhttp3 >> 请求数据类型 = {}", "MediaType >> application/x-www-form-urlencoded;charset=" + charset);
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数

        StringBuilder sb = new StringBuilder();
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                log.info("okhttp3 >> 请求参数 {} = {}", key, params.get(key));
                //builder.add(key, params.get(key));
                sb.append("&" + key + "=" + params.get(key));
            }
        }
        log.info("okhttp3 >> 开始请求......");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=" + charset), sb.toString()))
                .build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            log.info("okhttp3 >> 请求响应码 = {}", status);
            if (response.isSuccessful()) {
                String str = new String(response.body().bytes(), charset);
                log.info("okhttp3 >> 请求响应内容 = {}", str);
                return str;
            }
        } catch (Exception e) {
            log.error("okhttp3 >> 请求发送错误 = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
            log.info("okhttp3 >> 请求结束");
        }
        return responseBody;
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public static String postJsonParams(String url, String jsonParams) {
        String responseBody = "";
        log.info("okhttp3 >> Post请求发送JSON数据....");
        log.info("okhttp3 >> 请求类型 = POST");
        log.info("okhttp3 >> 请求地址URL = {}", url);
        log.info("okhttp3 >> 请求数据类型 = {}", "MediaType >> application/json; charset=utf-8");
        log.info("okhttp3 >> 请求参数 JSON 数据 = {}", jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        log.info("okhttp3 >> 开始请求......");
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            log.info("okhttp3 >> 请求响应码 = {}", status);
            if (response.isSuccessful()) {
                String str = response.body().string();
                log.info("okhttp3 >> 请求响应内容 = {}", str);
                return str;
            }
        } catch (Exception e) {
            log.error("okhttp3 >> 请求发送错误 = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
            log.info("okhttp3 >> 请求结束");
        }
        return responseBody;
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public static String postXmlParams(String url, String xml) {
        String responseBody = "";
        log.info("okhttp3 >> Post请求发送xml数据....");
        log.info("okhttp3 >> 请求类型 = POST");
        log.info("okhttp3 >> 请求地址URL = {}", url);
        log.info("okhttp3 >> 请求数据类型 = {}", "MediaType >> application/xml; charset=utf-8");
        log.info("okhttp3 >> 请求参数 xml 数据 = {}", xml);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        log.info("okhttp3 >> 开始请求......");
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            log.info("okhttp3 >> 请求响应码 = {}", status);
            if (response.isSuccessful()) {
                String str = response.body().string();
                log.info("okhttp3 >> 请求响应内容 = {}", str);
                return str;
            }
        } catch (Exception e) {
            log.error("okhttp3 >> 请求发送错误 = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
            log.info("okhttp3 >> 请求结束");
        }
        return responseBody;
    }


    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     *
     * @param URL url地址
     * @return url请求参数部分
     */
    public static Map<String, String> URLRequest(String URL) {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String[] arrSplit = null;

        String strUrlParam = TruncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        //每个键值为一组 www.2cto.com
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }


    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    public static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            } else {
                strAllParam = arrSplit[0];
            }
        } else {
            strAllParam = strURL;
        }

        return strAllParam;
    }

}

